
import { defineStore } from "pinia";
import { computed, ref } from "vue";


interface CartItem{
    id:string,
    imgUrl:string,
    name:string,
    newPrice:number,
    oldPrice:number,
    count:number,
    //设置checked默认值为true
    checked:boolean
}

export const useCartStore = defineStore("cart", ()=>{
    const cartList = ref<CartItem[]>([])
    const addCart = (item:CartItem)=>{
        if(cartList.value.find(item1=>item1.id === item.id)){
            cartList.value.find(item1=>item1.id === item.id)!.count++
            console.log(cartList.value);
            return
        }
        cartList.value.push(item)
    }
    const delCart = (id:string)=>{
        cartList.value = cartList.value.filter(item=>item.id !== id)
    }
    const clearCart = ()=>{
        cartList.value = []
    }
    // 计算总价
    const totalPrice = ()=>{
        return cartList.value.reduce((acc,item)=>acc+item.newPrice*item.count,0)
    }
    //改变某个商品的数量
    const changeCount = (id:string,count:number)=>{
        const item = cartList.value.find(item=>item.id === id)
        if(item){
            item.count = count
        }
    }
    //改变所有商品的选中状态
    const changeAllchecked = (checked:boolean)=>{
        cartList.value.forEach(item=>item.checked = checked)
    }
    //查看是否全部选中
    const isAllChecked = computed({
        get(){
            return cartList.value.every(item=>item.checked)
        },
        set(val){
            //将所有商品的checked设置为val
            changeAllchecked(val)
        }
    })
    //计算被选中的商品数量
    const checkedCount = computed(()=>{
        return cartList.value.filter(item=>item.checked).reduce((acc,item)=>acc+item.count,0)
    })

    //计算被选中的商品总价
    const checkedPrice = computed(()=>{
        return cartList.value.filter(item=>item.checked).reduce((acc,item)=>acc+item.newPrice*item.count,0)
    })

    //返回所有被选中的商品
    const checkedList = computed(()=>{
        return cartList.value.filter(item=>item.checked)
    })

    //计算总数量
    const totalCount = computed(()=>{
        return cartList.value.reduce((acc,item)=>acc+item.count,0)
    })
    
    return {
        cartList,
        addCart,
        delCart,
        clearCart,
        totalPrice,
        changeCount,
        changeAllchecked,
        checkedList,
        checkedPrice,
        isAllChecked,
        checkedCount,
        totalCount
    }
},{
    persist:{
        enabled:true,
        storage:sessionStorage,
        paths:['cartList'] // 只持久化cartList
    }
});